package com.reader.api.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author liujianqing
 * @date 2018/10/24
 */
public class IpUtils {
    private static final String FORWARD_SEPARATOR = ",";

    public static String ip = null;

    private static String ipSuffix = null;

    private static String hostName = null;

    static {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostName = addr.getHostName();
            ip = addr.getHostAddress().toString();

            if (StringUtils.isNotBlank(ip)) {
                int start = ip.indexOf(".", ip.indexOf(".") + 1) + 1;
                if (start < ip.length() && start > 0) {
                    ipSuffix = ip.substring(start);
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static String getLocalHostName() {
        return hostName;
    }

    public static String getLocalIP() {
        return ip;
    }

    public static String getLocalIPSuffix() {
        return ipSuffix;
    }

    public static String findIpFromRequest(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");

        /*ng*/
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        } else {
            return ip;
        }
        /*proxy*/
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        } else {
            //处理x-forwarded-for，多级反向代理，取第一个
            int indexOfSeparator = ip.indexOf(FORWARD_SEPARATOR);
            if (indexOfSeparator != -1) {
                ip = ip.substring(0, indexOfSeparator);
            }
            return ip;
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        } else {
            return ip;
        }

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        } else {
            return ip;
        }

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return StringUtils.defaultString(ip);
    }

}
